package com.lcx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.lcx.entity.Musics;
import com.lcx.entity.dto.SwiperDto;
import com.lcx.mapper.MusicsMapper;
import com.lcx.service.IMusicsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2023-11-09
 */
@Service
public class MusicsServiceImpl extends ServiceImpl<MusicsMapper, Musics> implements IMusicsService {

    
    @Autowired
    private MusicsMapper mapper;
    String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9273455549562cc4&secret=33205d5793204e43c017696587525919";
    @Override
    public List<SwiperDto> findSwiperList () {
        return mapper.selectSwiperList();
    }
    
 
    @Override
    public Object addMusic (HttpServletRequest request, MultipartFile file) throws IOException {
        /*String parameter = request.getParameter("filePath");
        System.out.println("parameter = " + parameter);
      
        if (!file.isEmpty()) {
            //上传文件路径
//            String path = request.getServletContext().getRealPath("/uploadFiles/");
            String path = "G:/upload";
            //获得上传文件名
            String fileName = file.getOriginalFilename();
            File filePath = new File(path + File.separator + fileName);

            System.out.println(filePath);
            //如果文件目录不存在，创建目录
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件中
            file.transferTo(filePath);
            return fileName;
            https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9273455549562cc4&secret=33205d5793204e43c017696587525919
        }*/
        
        String accessToken = getToken(TOKEN_URL);

        String url = "https://api.weixin.qq.com/tcb/uploadfile?access_token=" + accessToken;// service.getAccessToken();
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");

        JsonObject req = new JsonObject();
        req.addProperty("env", "prod-0g36g611fc13d81b"); // 云开发环境 从小程序-云开发面板里面找到
        req.addProperty("path", "metest/music"); // 上传的路径，实际上没鸟用，上传文件需要再次指定
        StringEntity entity = new StringEntity(req.toString());
        httpPost.setEntity(entity);
        org.apache.http.HttpResponse response1;
        response1 = httpClient.execute(httpPost);
        InputStream inputStream = response1.getEntity().getContent();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int bytesRead = 0;
        while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
        out.flush();
        out.close();
        //out转换为json
        String s = String.valueOf(out);
        JSONObject jsonObject = JSON.parseObject(s);
        RestTemplate template = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);
        //获取文件名
        String filename = file.getOriginalFilename();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        /*路径*/
        //获取文件后缀
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        System.out.println(filename);
        Map<String,String> map1=new HashMap<>();
        if (suffix.equals("mp3") || suffix.equals("wav") || suffix.equals("flac") || suffix.equals("ape")){
            
            map.add("key", "metest/music/"+filename);

            map1.put("url","/metest/music/"+filename);
        } else if (suffix.equals("mp4")) {
            
            map.add("key", "metest/video/"+filename);
            
            map1.put("url","/metest/video/"+filename);

        }else if (suffix.equals("jpg") || suffix.equals("png") || suffix.equals("jpeg")) {
            
            map.add("key", "metest/轮播图/"+filename);
            
            map1.put("url","/metest/轮播图/"+filename);

        }
        map.add("Signature", jsonObject.get("authorization"));
        map.add("x-cos-security-token", jsonObject.get("token"));
        map.add("x-cos-meta-fileid", jsonObject.get("cos_file_id"));
        map.add("file", file.getBytes());
        
        

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, httpHeaders);
        
        url = (String) jsonObject.get("url");
        ResponseEntity<Object> responseEntity = template.postForEntity(url, httpEntity, Object.class);
        
        
        map1.put("name",filename);
        
        return map1;
    }
    public String getToken(String url){
        //发送请求
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(forObject);
        return (String) jsonObject.get("access_token");
    }
}
